package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.ActivityDO;
import com.tiance.dal.dataobject.PublishInfoDO;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.domain.ActivityDomain;
import com.tiance.domainservice.service.ActivityService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.utils.DateUtils;
import com.tiance.utils.Validator;
import com.tiance.vo.PublishInfoVO;
import com.tiance.vo.SignInVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.domainservice.checker.ActivityChecker;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import com.tiance.vo.ActivityVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：活动管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front/activity")
public class ActivityController extends FrontController{

    private static String LOG_PREFIX ="ActivityController| 活动控制器===>";

    @Autowired
    private ActivityService activityService;


    @RequestMapping(value = "/toActivity.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到活动页面")
    public String toActivity() {
        return "/front/activity";

    }

    @RequestMapping(value = "/toRegactivity.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到报名活动页面")
    public String toRegactivity() {
        return "/front/regactivity";

    }


    @RequestMapping(value = "/toAppactivity.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到活动申请页面")
    public String toAppactivity(Model model) {
        model.addAttribute("activityVO",new ActivityVO());
        return "/front/appactivity";

    }





    @RequestMapping(value = "/cancelActivity.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消活动")
    public BaseResponse cancelActivity(ActivityVO activityVO){
        logger.info("开始取消活动，请求参数:{}", JSON.toJSONString(activityVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(activityVO.getId(),"活动ID不能为空!");
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            activityDomain.setActivityStatus(ActivityStatusEnum.APPLY_CANCEL.getCode());
            if(MapCacheUtil.lock(activityVO.getId() + EntityTypeEnum.ACTIVITY.getCode())) {
                activityService.cancel(activityDomain);
            }else {
                throw new BusinessException("该活动正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消活动失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"取消活动失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("取消活动失败");
        }finally {
            MapCacheUtil.unlock(activityVO.getId() + EntityTypeEnum.ACTIVITY.getCode());
        }
        logger.info("结束取消活动，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }



    @RequestMapping(value = "/addActivity.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="插入活动")
    public String addActivity(HttpServletRequest request, Model model, ActivityVO activityVO){
        logger.info("开始插入活动，请求参数:{}", JSON.toJSONString(activityVO));
        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                activityVO.setApplicantId((Long)memberId);
            }
            activityVO.setApplicantType(ApplicantTypeEnum.MEMBER.getCode());
            ActivityChecker.checkAddActivity(activityVO);
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            activityService.addActivity(activityDomain);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"插入活动失败，失败原因：",e1);
            activityVO.setErrorInfo(e1.getMessage());
            model.addAttribute("activityVO",activityVO);
            return  "/front/appactivity";
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"插入活动失败,失败原因",e2);
            activityVO.setErrorInfo("插入活动失败,请稍后重试!");
            model.addAttribute("activityVO",activityVO);
            return "/front/appactivity";
        }
        logger.info("结束插入活动，返回数据:{}", model);
        return "/front/activity";

    }


    @RequestMapping(value = "/querySignUpActivityList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员报名的活动")
    public BaseResponse querySignUpActivityList(HttpServletRequest request, ActivityVO activityVO, QueryPage queryPage){
        logger.info("开始查询会员报名的活动，请求参数:{}", JSON.toJSONString(activityVO));
        BaseResponse<ActivityVO> response=new BaseResponse();

        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                activityVO.setApplicantId((Long)memberId);
            }

            MemberParamsChecker.checkPageQuery(queryPage);
            activityVO.setQueryPage(queryPage);
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            List<ActivityDO> activityList= activityService.querySignUpActivityList(activityDomain);

            List<ActivityVO> activityVOList=new ArrayList<>(activityList.size());
            if(!CollectionUtils.isEmpty(activityList)){
                for(ActivityDO activityDO:activityList){
                    ActivityVO activityVO1=new ActivityVO();
                    BeanConverterUtil.copyProperties(activityVO1, activityDO);
                    if(null!=activityDO.getCreateTime()){
                        activityVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(activityDO.getCreateTime()));
                    }
                    if(null!=activityDO.getUpdateTime()){
                        activityVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(activityDO.getUpdateTime()));
                    }

                    activityVOList.add(activityVO1);
                }
            }

            response.setSuccess(true);
            response.setMessage("查询报名活动成功!");
            response.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            response.setResultList(activityVOList);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"活动查询失败，失败原因：",e1);
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"活动查询失败,失败原因",e2);
        }
        logger.info("结束查询会员报名的活动，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }


    @RequestMapping(value = "/queryApplyActivityList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员申请的活动")
    public BaseResponse queryApplyActivityList(HttpServletRequest request, ActivityVO activityVO, QueryPage queryPage){
        logger.info("开始查询活动列表，请求参数:{}", JSON.toJSONString(activityVO));

        BaseResponse<ActivityVO> backResponse=new BaseResponse<>();
        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                activityVO.setApplicantId((Long)memberId);
            }

            MemberParamsChecker.checkPageQuery(queryPage);
            activityVO.setQueryPage(queryPage);
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            List<ActivityDO> applyActivityList= activityService.queryApplyActivity(activityDomain);
            List<ActivityVO> activityVOList=new ArrayList<>(applyActivityList.size());
            if(!CollectionUtils.isEmpty(applyActivityList)){
                for(ActivityDO activityDO:applyActivityList){
                    ActivityVO activityVO1=new ActivityVO();
                    BeanConverterUtil.copyProperties(activityVO1, activityDO);
                    if(null!=activityDO.getCreateTime()){
                        activityVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(activityDO.getCreateTime()));
                    }
                    if(null!=activityDO.getUpdateTime()){
                        activityVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(activityDO.getUpdateTime()));
                    }

                    activityVOList.add(activityVO1);
                }
            }

            backResponse.setResultList(activityVOList);
            backResponse.setQueryPage(activityDomain.getQueryPage());
            backResponse.setTotalRecord(applyActivityList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询活动列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询活动列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询活动列表失败");
        }
        logger.info("结束查询活动列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }

}